package com.system.runtai.controller;

import com.system.common.result.Result;
import io.swagger.annotations.Api;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Objects;
import java.util.UUID;

/**
 * @author luYuHan
 * @date 2023/8/5 22:26
 */
@CrossOrigin(origins = "*")
@Controller
@Api(tags = "文件下载")
@RequestMapping("/runtai/file/upload")
public class MyFileUploadController {


    @Value("${urlVideo}")
    private String basePath;

    @PostMapping ("/part")
    @ResponseBody
    public Result bigFile(HttpServletRequest request, String guid, Integer chunk,  MultipartFile file, Integer chunks) {
        try {
            String projectUrl = System.getProperty("user.dir").replaceAll("\\\\", "/");
            boolean isMultipart = ServletFileUpload.isMultipartContent(request);
            if (isMultipart){
                if (chunk==null) chunk=0;
                // 临时目录用来存放所有分片文件
                String tempFileDir = projectUrl + "/upload/"+guid;
                File parentFileDir = new File(tempFileDir);
                if (!parentFileDir.exists()) {
                    parentFileDir.mkdirs();
                }
                // 存放临时文件
                FileUtils.copyInputStreamToFile(file.getInputStream(), new File(parentFileDir,guid+"_chunk"+chunk+".part"));
            }
        } catch (IOException e) {
            Result.fail().message("上传失败");
        }
        return Result.ok().message("上传成功");
    }


    @PostMapping("/load")
    @ResponseBody
    public Result uploadFile(HttpServletRequest request, MultipartFile file) {

        String filename = null;
        try {
            //获取文件名
            String originalFilename = file.getOriginalFilename();
            //获取文件格式
            String subFile = originalFilename.substring(originalFilename.lastIndexOf("."));
            //生成随机的文件名字
            filename = UUID.randomUUID().toString() + subFile;
            boolean isMultipart = ServletFileUpload.isMultipartContent(request);
            if (isMultipart) {
                File file1 = new File(basePath);
                //判断存放图片的目录是否存在，不存在则进行创建
                if (!file1.exists()) {
                    file1.mkdirs();
                }
                try {
                    //错误示范
//            file.transferTo(new File(file1 + filename));
                    //将临时文件转存到指定位置
                    FileUtils.copyInputStreamToFile(file.getInputStream(), new File(basePath + filename));
//                    file.transferTo(new File(basePath + filename));
                } catch (IOException e) {
                    e.printStackTrace();
                }

            }
        }catch (Exception e) {
            Result.fail(filename).message("上传失败");
        }
                return Result.ok(filename).message("上传成功");
    }


    /**
     * 文件下载
     * @param name
     * @param response
     */
//    @GetMapping("/download")
//    @ResponseBody
//    public void download(String name, HttpServletResponse response) {
//        try {
//            FileInputStream fileInputStream = new FileInputStream(new File(basePath + name));
//            //输出流，通过输出流将文件写回浏览器
//            ServletOutputStream outputStream = response.getOutputStream();
//
//            response.setContentType("video/mp4");
//
////            String suffixName = name.substring(name.lastIndexOf("."));
////            File finalFile = new File(basePath+suffixName);
////////            response.setContentType("image/jpeg");
////////            response.setContentType("video/mp4");
////            File allfile = new File(basePath);
////            for (File file : Objects.requireNonNull(allfile.listFiles())) {
////                fileOutputStream = new FileOutputStream(finalFile,true);
////                long l = FileUtils.copyFile(file, fileOutputStream);
////
////                outputStream.write((int) l);
////                outputStream.flush();
////            }
////            int len = 0;
//            File finalFile = new File(basePath+name.substring(name.lastIndexOf(".")));
//            FileOutputStream fileOutputStream = null;
//            File allfile = new File(basePath+name);
//            for (File file : Objects.requireNonNull(allfile.listFiles())) {
//                fileOutputStream = new FileOutputStream(finalFile,true);
//                long l = FileUtils.copyFile(file, fileOutputStream);
//                outputStream.write((int) l);
//                outputStream.flush();
//            }
//
//            fileOutputStream.close();
//            outputStream.close();
//            fileInputStream.close();
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
//
//
//    }


    @GetMapping("/download")
    public void download(String name, HttpServletResponse response) {
        try {
            FileInputStream fileInputStream = new FileInputStream(new File(basePath + name));
            //输出流，通过输出流将文件写回浏览器
            ServletOutputStream outputStream = response.getOutputStream();

//            response.setContentType("image/jpeg");
            response.setContentType("video/mp4");
            int len;
//            byte[] bytes = new byte[1024];
            byte[] bytes = new byte[8192];
            while ((len = fileInputStream.read(bytes)) != -1){
                outputStream.write(bytes,0,len);
                outputStream.flush();
            }
            outputStream.close();
            fileInputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @GetMapping("merge")
    @ResponseBody
    public Result mergeFile(String guid, String fileName) {
        try {
            // 得到 destTempFile 就是最终的文件
            String projectUrl = System.getProperty("user.dir").replaceAll("\\\\", "/");
            String suffixName = fileName.substring(fileName.lastIndexOf("."));
            String finaFileName = projectUrl + "/upload/" + UUID.randomUUID() + suffixName;
            String temFileDir = projectUrl + "/upload/" + guid;
            File finalFile = new File(finaFileName);
            File allfile = new File(temFileDir);
            for (File file : Objects.requireNonNull(allfile.listFiles())) {
                FileOutputStream fileOutputStream = new FileOutputStream(finalFile,true);
                FileUtils.copyFile(file,fileOutputStream);
                fileOutputStream.close();
            }
        } catch (IOException e) {
            return Result.fail().message("合并失败");
        }
        return Result.ok().message("合并成功");

    }


}
